<template>
  <div>
    <canvas id="canvas"></canvas>
  </div>
  <div class="operation_container">
    <span class="text-start mb-3">线条</span>
    <button id="clearLines" class="btn btn-primary">清除线条</button>
    <button id="rollbackLines" class="btn btn-primary mt-3">线条回退</button>

    <span class="text-start mt-3">场地</span>
    <div class="btn-group mt-3" role="group" aria-label="Basic example">
      <button type="button" id="selectRedCourt" class="btn btn-danger">
        红土
      </button>
      <button type="button" id="selectHardCourt" class="btn btn-primary">
        硬地
      </button>
      <button type="button" id="selectGrassCourt" class="btn btn-success">
        草地
      </button>
    </div>

    <span class="text-start mt-3">视频</span>
    <div class="btn-group mt-3" role="group" aria-label="Basic example">
      <button type="button" id="startRecording" class="btn btn-success">
        开始录制
      </button>
      <button type="button" id="stopRecording" class="btn btn-danger">
        停止录制
      </button>
    </div>
  </div>
  <div class="video_container">
    <video id="recordedVideo" controls></video>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";

import player_opponent_img from "@/assets/player_duishou.png";
import player_me_img from "@/assets/player_me.png";
import red_court_img from "@/assets/court_red.png";
import hard_court_img from "@/assets/court_blue.png";
import grass_court_img from "@/assets/court_green.png";

import { Player } from "./element/player";

const canvasRef = ref(null);

const imageUrls = [red_court_img, player_opponent_img, player_me_img, hard_court_img, grass_court_img];

onMounted(() => {
  const canvas = document.getElementById("canvas");
  canvas.width = 1080;
  canvas.height = 1920;
  const ctx = canvas.getContext("2d");

  const clearLinesButton = document.getElementById("clearLines");
  const rollbackLinesButton = document.getElementById("rollbackLines");
  const startButton = document.getElementById("startRecording");

  const selectRedCourtButton = document.getElementById("selectRedCourt");
  const selectHardCourtButton = document.getElementById("selectHardCourt");
  const selectGrassCourtButton = document.getElementById("selectGrassCourt");

  const stopButton = document.getElementById("stopRecording");
  const recordedVideo = document.getElementById("recordedVideo");

  let mediaRecorder;
  let recordedChunks = [];

  const images = [];
  let imagesLoaded = 0;

  function imageLoaded() {
    imagesLoaded++;
    if (imagesLoaded === imageUrls.length) {
      // 所有图片加载完成，开始绘制
      redraw();
    }
  }

  imageUrls.forEach((url, index) => {
    const img = new Image();
    img.src = url;
    img.onload = imageLoaded; // 当图片加载完毕时调用 imageLoaded 函数
    images[index] = img;
  });

  const [redCourtImage, playerOpponentImg, playerMeImg, hardCourtImage, grassCourtImage] = images

  // 保存曲线（自由绘画）的数组，每个路径包括多个点、颜色和粗细
  let drawings = [];
  let currentPath = []; // 当前的路径
  let currentColor = "black";

  let isDrawing = false;
  let isPlayOpponentDragging = false;
  let isPlayMeDragging = false;

  let backgroundImage = redCourtImage
  let playerOpponent = new Player(400, 200, playerOpponentImg);
  let playerMe = new Player(700, 1400, playerMeImg);

  // 开始绘制
  canvas.addEventListener("mousedown", (e) => {
    const mousePos = getMousePos(canvas, e);

    // Check if the click is inside the image
    if (playerOpponent.isInsideImage(mousePos)) {
      isPlayOpponentDragging = true;
      playerOpponent.setOffset(
        mousePos.x - playerOpponent.x,
        mousePos.y - playerOpponent.y
      );
    } else if (playerMe.isInsideImage(mousePos)) {
      isPlayMeDragging = true;
      playerMe.setOffset(mousePos.x - playerMe.x, mousePos.y - playerMe.y);
    } else {
      isDrawing = true;
      currentPath = []; // 开始新的路径
      const color = currentColor;
      const lineWidth = 10;
      currentPath.push({
        x: mousePos.x,
        y: mousePos.y,
        color: color,
        lineWidth: lineWidth,
      });
    }
  });

  // 绘制线条
  canvas.addEventListener("mousemove", (event) => {
    const mousePos = getMousePos(canvas, event);

    if (isPlayOpponentDragging) {
      playerOpponent.refreshXY(mousePos);
      redraw();
    } else if (isPlayMeDragging) {
      playerMe.refreshXY(mousePos);
      redraw();
    } else if (isDrawing) {
      // 保存当前鼠标位置
      currentPath.push({
        x: mousePos.x,
        y: mousePos.y,
      });

      // 绘制当前曲线
      const lastPoint = currentPath[currentPath.length - 2];
      const currentPoint = currentPath[currentPath.length - 1];
      ctx.strokeStyle = currentPath[0].color;
      ctx.lineWidth = currentPath[0].lineWidth;
      ctx.beginPath();
      ctx.moveTo(lastPoint.x, lastPoint.y);
      ctx.lineTo(currentPoint.x, currentPoint.y);
      ctx.stroke();
    }
  });

  // 停止绘制
  canvas.addEventListener("mouseup", () => {
    isDrawing = false;
    isPlayMeDragging = false;
    isPlayOpponentDragging = false;
    ctx.closePath(); // 关闭当前路径
    if (currentPath.length > 0) {
      drawings.push([...currentPath]); // 保存整条路径（曲线）
    }
  });

  document.addEventListener("keydown", function (event) {
    switch (event.key) {
      case "r": // 按 'r' 键设置红色
        currentColor = "red";
        break;
      case "g": // 按 'g' 键设置绿色
        currentColor = "green";
        break;
      case "b": // 按 'b' 键设置蓝色
        currentColor = "blue";
        break;
      case "k": // 按 'k' 键设置黑色
        currentColor = "black";
        break;
    }
    console.log("当前颜色：", currentColor);
  });

  function redraw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas

    ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
    playerOpponent.draw(ctx);
    playerMe.draw(ctx);

    // 遍历并重新绘制所有保存的路径
    drawings.forEach((path) => {
      ctx.strokeStyle = path[0].color;
      ctx.lineWidth = path[0].lineWidth;

      for (let i = 1; i < path.length; i++) {
        ctx.beginPath();
        ctx.moveTo(path[i - 1].x, path[i - 1].y);
        ctx.lineTo(path[i].x, path[i].y);
        ctx.stroke();
      }
    });
  }

  function getMousePos(canvas, evt) {
    console.log(evt);
    const rect = canvas.getBoundingClientRect();
    console.log(rect);
    return {
      x: (evt.clientX - rect.left) * 2,
      y: (evt.clientY - rect.top) * 2,
    };
  }

  startButton.addEventListener("click", () => {
    const stream = canvas.captureStream(30); // Capture canvas at 30fps
    mediaRecorder = new MediaRecorder(stream);

    mediaRecorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        recordedChunks.push(event.data);
      }
    };

    mediaRecorder.onstop = () => {
      const blob = new Blob(recordedChunks, { type: "video/mp4" });
      recordedChunks = [];
      const videoURL = URL.createObjectURL(blob);
      recordedVideo.src = videoURL; // Display recorded video
      recordedVideo.download = "recording.mp4";

      const a = document.createElement("a");
      a.href = videoURL;
      a.download = "recording.mp4";
      a.click();
    };

    mediaRecorder.start();
  });

  stopButton.addEventListener("click", () => {
    mediaRecorder.stop();
  });

  clearLinesButton.addEventListener("click", () => {
    drawings = [];
    currentPath = [];
    redraw();
  });

  rollbackLinesButton.addEventListener("click", () => {
    drawings.pop();
    redraw();
  });

  selectRedCourtButton.addEventListener("click", () => {
    backgroundImage = redCourtImage
    redraw();
  })

  selectHardCourtButton.addEventListener("click", () => {
    backgroundImage = hardCourtImage
    redraw();
  })

  selectGrassCourtButton.addEventListener("click", () => {
    backgroundImage = grassCourtImage
    redraw();
  })
});
</script>

<style lang="scss">
body,
html {
  margin: 0;
  padding: 0;
}
#app {
  display: flex;

  .operation_container {
    padding: 50px;
    display: flex;
    flex-direction: column;
  }
}
canvas {
  width: 540px;
  height: 960px;
  display: block;
}

video {
  width: 540px;
  height: 960px;
  display: block;
}
</style>
